package org.example.socket网络编程.练习_拷贝文件夹;


import java.io.*;

public class PackageCopy {
    static String sourceDir = "D:\\idea project\\study\\src\\main\\java\\org\\example\\socket网络编程";
    static String targetDir = "D:\\idea project\\study\\src\\main\\java\\org\\example\\2";

    public static void main(String[] args) {
        copyDir();
    }

    public static void copyDir(){
        File sourceFileDir = new File(sourceDir);
        File targetFileDir = new File(targetDir);
        copy(sourceFileDir, targetFileDir);
    }

    public static void copy(File source, File target){
        if(!target.exists()){
            target.mkdir();
        }
        File[] files = source.listFiles();
        if (files != null) {
            for (File file : files) {
                // 新文件路径 = 新目录地址 + 老文件名
                File newFile = new File(target, file.getName());
                // 文件
                if(file.isFile()){
                    try(
                        InputStream fileInputStream = new FileInputStream(file);
                        OutputStream fileOutputStream = new FileOutputStream(newFile))
                    {
                        // 读取文件
                        int len = 0;
                        byte[] bytes = new byte[1024];
                        while( (len = fileInputStream.read(bytes)) != -1 ){
                            // 写新文件
                            fileOutputStream.write(bytes, 0 , len);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else { // 文件夹
                    copy(file, newFile);
                }
            }
        }
    }

}










